﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Besture.Common;
using Besture.Common.Definition;

using Besture.Bll;
using Besture.Model;

namespace Besture.UI
{
    /// <summary>
    /// WebPage:无登录验证
    /// </summary>
    public abstract class WebPage : Page
    {
        /// <summary>
        /// 编辑页面-编号
        /// </summary>
        public int ID;
        /// <summary>
        /// 编辑页面标识
        /// </summary>
        public bool EditPage = false;

        /// <summary>
        /// 用户Id
        /// </summary>
        public int UserId
        {
            get { return HttpContext.Current.Session[Constants.SESSION_WEB_USER_MODEL] == null ? 0 : ((UserBaseModel)HttpContext.Current.Session[Constants.SESSION_WEB_USER_MODEL]).ID; }
        }

        /// <summary>
        /// 用户信息
        /// </summary>
        protected UserBaseModel LoginUserInfo
        {
            get { return HttpContext.Current.Session[Constants.SESSION_WEB_USER_MODEL] == null ? null : (UserBaseModel)HttpContext.Current.Session[Constants.SESSION_WEB_USER_MODEL]; }
        }
        ///<summary>
        /// 初始化
        ///</summary>
        ///<remarks></remarks>
        protected override void OnLoad(System.EventArgs e)
        {
            //SEO
            if (Request.Url.LocalPath.Length > 0)
            {
                var pageName = Request.Url.LocalPath;
                //根据页面名称获取SEO
                var seoModel = new SeoDac().GetModel(pageName);
                if (seoModel != null)
                {
                    this.Title = seoModel.SeoTitle;
                    this.MetaDescription = seoModel.SeoDescription;
                    this.MetaKeywords = seoModel.SeoKeywords;
                }
            }

            if (!base.IsPostBack)
            {

                this.InitialLoad();
                this.SetErrorMessageOnLoad();
            }
            else
            {
                this.PostBackLoad();
            }
            base.OnLoad(e);
        }


        /// <summary>
        /// 设置SEO
        /// </summary>
        /// <param name="title"></param>
        /// <param name="description"></param>
        /// <param name="keywords"></param>
        protected void GetPageSeo(string title, string keywords, string description)
        {
            if (!string.IsNullOrEmpty(title) )
            {
                this.Title = title;
            }
            if (!string.IsNullOrEmpty(keywords) )
            {
                this.MetaKeywords = keywords;
            }
            if (!string.IsNullOrEmpty(description))
            {
                this.MetaDescription = description;
            }
        }

        /// <summary>
        /// 锁定导航
        /// </summary>
        /// <param name="index"></param>
        protected void GetLockNavigation(int index)
        {
            ((HiddenField)Master.FindControl("hfMasterOn")).Value = index.ToString();
        }


        /// <summary>
        /// 捕捉页面错误
        /// </summary>
        /// <param name="e"></param>
        protected override void OnError(EventArgs e)
        {
            //捕捉页面错误
            string message = Server.GetLastError().GetBaseException().Message;
            WriteLog(message);
        }


        #region 基本共通方法
        /// <summary>
        /// 查询URL参数
        /// </summary>
        /// <param name="param">参数KEY</param>
        /// <returns></returns>
        public string Query(string param)
        {
            if (Request.QueryString[param] == null)
            {
                return string.Empty;
            }
            else
            {
                return Request.QueryString[param];
            }
        }

        /// <summary>
        /// 锁定导航
        /// </summary>
        /// <param name="index">当前位置</param>
        /// <returns></returns>
        public void LockNavigation(string index)
        {
            ((HiddenField) Master.FindControl("hfOn")).Value = index;
        }

        /// <summary>
        /// 后台登录页面
        /// </summary>
        /// <returns></returns>
        public static string LoginUrl()
        {
            return string.Format(@"{0}?returnUrl={1}", AppSettings.ADMIN_LOGIN, HttpContext.Current.Server.UrlEncode(HttpContext.Current.Request.Url.PathAndQuery));
        }

        /// <summary>
        /// 前台登录页面
        /// </summary>
        /// <returns></returns>
        public static string WebLoginUrl()
        {
            return string.Format(@"{0}?returnUrl={1}", AppSettings.WEB_ADMIN_LOGIN, HttpContext.Current.Server.UrlEncode(HttpContext.Current.Request.Url.PathAndQuery));
            return "";
        }

        /// <summary>
        /// 页面JS弹出提示
        /// </summary>
        /// <param name="page"></param>
        /// <param name="tips"></param>
        protected void PageAlert(string tips)
        {
            string scriptStr = string.Format(@"<script>Alter('{0}');</script>", tips);
            ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", scriptStr);
        }
        #endregion

        #region 系统

        /// <summary>
        /// Write out log
        /// </summary>
        /// <param name="sMessage">content of log</param>
        public void WriteLog(string sMessage)
        {
            Besture.Common.Logging.AppLogger.TraceLog(sMessage);
        }

        ///<summary>
        /// set error message for validation when initial loading
        ///</summary>
        ///<remarks>the method should be overrode if the page has validation</remarks>
        protected virtual void SetErrorMessageOnLoad()
        { }

        ///<summary>
        /// 初始化
        ///</summary>
        ///<remarks>This method must be implemented.</remarks>
        protected abstract void InitialLoad();
        ///<summary>
        /// 回传
        ///</summary>
        ///<remarks>This method must be implemented.</remarks>
        protected abstract void PostBackLoad();

        public delegate void EventHandlerPageChange(object sender, CommandEventArgs e);
        public event BasePage.EventHandlerPageChange Click;
        protected void OnClick(CommandEventArgs e)
        {
            if (Click != null) Click(this, e);
        }
        #endregion

        #region 缓存

        public void SetCache(string key, object obj)
        {
            HttpContext.Current.Cache.Insert(key, obj);
        }

        #endregion

        #region ---跳转页面---

        /// <summary>
        /// 分析列表页面
        /// </summary>
        /// <returns></returns>
        protected string ListUrl()
        {
            return HttpContext.Current.Request.Path.ToLower().Replace("set.aspx", "list.aspx");
        }

        /// <summary>
        /// 分析编辑页面
        /// </summary>
        /// <returns></returns>
        protected string SetUrl()
        {
            return HttpContext.Current.Request.Path.ToLower().Replace("list.aspx", "set.aspx");
        }

        /// <summary>
        /// 跳转列表页面
        /// </summary>
        protected void RedirectListUrl(bool alertFlag)
        {
            string listUrl = ListUrl();
            if (alertFlag)
            {
                RedirectUrl(listUrl, "保存成功");
            }
            else
            {
                RedirectUrl(listUrl);
            }
        }


        /// <summary>
        /// 跳转URL
        /// </summary>
        /// <param name="url"></param>
        protected void RedirectUrl(string url)
        {
            Response.Redirect(url);
        }

        /// <summary>
        /// 提示后跳转到URL页面
        /// </summary>
        /// <param name="str"></param>
        /// <param name="url"></param>
        public static void RedirectUrl(string url, string str)
        {
            HttpContext.Current.Response.Write("<script language='JavaScript'>");
            if (str != null)
            {
                HttpContext.Current.Response.Write(" alert('" + str + "');");
            }
            if (url != null)
            {
                HttpContext.Current.Response.Write(" location.href='" + url + "';");
            }
            HttpContext.Current.Response.Write("</script>");
        }

        /// <summary>
        /// 跳转错误页面
        /// </summary>
        /// <param name="errorStr"></param>
        protected void RedirectErrorUrl(string errorStr)
        {
            Response.Redirect("/Admin/Error.aspx");
        }

        #endregion

        #region 其它

        /// <summary>
        /// 是否数字
        /// </summary>
        /// <param name="lstr"></param>
        /// <returns></returns>
        public bool IsNumber(string lstr)
        {
            bool isDecimal = false;
            for (int i = 0; i < lstr.Length; i++)
            {
                char ochar = lstr[i];
                if (i == 0 && ochar == '-')
                    continue;
                if (ochar == '.' && !isDecimal)
                {
                    isDecimal = true;
                    continue;
                }
                if (ochar < '0' || ochar > '9')
                {
                    return false;
                }
            }
            return true;
        }

        #endregion

    }
}
